package com.example.admin.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class WebSocketHandler extends TextWebSocketHandler {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);

    @Autowired
    private WebSocketSessionMessage webSocketSessionMessage;

    /**
     * 当WebSocket连接建立后调用此方法
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        webSocketSessionMessage.addSession(webSocketSession);
    }

    /**
     * 处理接收到的文本消息
     */
    @Override
    public void handleTextMessage(WebSocketSession webSocketSession, TextMessage textMessage) throws Exception {
        String payload = textMessage.getPayload();
        String userIP = webSocketSession.getRemoteAddress().getAddress().getHostAddress();
        webSocketSessionMessage.broadcastMessage("用户[" + webSocketSession.getId() + "]来自IP[" + userIP + "]发送的消息: " + payload);
        logger.info("用户: {}, 来自IP: {}, 发送的消息: {}", webSocketSession.getId(), userIP, payload);
    }

    /**
     * 当WebSocket连接关闭后调用此方法
     */
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        webSocketSessionMessage.removeSession(webSocketSession);
    }

}
